package com.csoa.community.services;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.csoa.community.R;
import com.csoa.community.net.ErrorMsg;
import com.csoa.community.singletons.GlobalVars;
import com.csoa.community.utils.AndroidUtils;
import com.csoa.community.utils.ConvertUtils;
import com.csoa.community.utils.IOUtils;
import com.csoa.community.utils.StringUtils;
import com.csoa.community.utils.IOUtils.MyDownloadListener;

public class UpgradeService extends Service {
	private NotificationManager nm;
	private String downUrl;
	private String FileName;
	private int totalSize;
	private String AttachID;
	private String FileExtend;
	private String ID;
	private String FileType;
	private String fromEmail;

	@Override
	public IBinder onBind(Intent i) {
		return null;
	}

	@Override
	public void onCreate() {
		init();
	}

	private void init() {
		nm = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		ID = intent.getStringExtra("ID");
		if(!StringUtils.isEmpty(ID)) {
			FileType = intent.getStringExtra("FileType");
			FileName = intent.getStringExtra("A_ORIGINAL_FILENAME");
//			if(FileType.contains("tif")) {
//				FileType = ".jpg";
//			}
			downUrl = "http://www.cshb.gov.cn/CsWebMobile/Archives/" + ID + FileType;
		}else {
			AttachID = intent.getStringExtra("AttachID");
			FileExtend = intent.getStringExtra("FileExtend");
			FileName = intent.getStringExtra("FileName");
			fromEmail = intent.getStringExtra("fromemail");
//			if(FileExtend.contains("tif")) {
//				FileExtend = ".jpg";
//			}
			
			if(!StringUtils.isEmpty(fromEmail) && fromEmail.equals("fromemail")) {
				downUrl = "http://www.cshb.gov.cn/CsWebMobile/Mail/" + AttachID + FileExtend;
			}else {
				downUrl = "http://www.cshb.gov.cn/CsWebMobile/Document/" + AttachID + FileExtend;
			}
			
		}
//		downUrl = intent.getStringExtra("downUrl");
		startDownloadingTask();
		return super.onStartCommand(intent, flags, startId);
	}

	private void startDownloadingTask() {
		showNotification();
		new AsyncDownLoadTask().execute();
	}

	private class AsyncDownLoadTask extends AsyncTask<Object,Object,Object> {

		@Override
		protected Object doInBackground(Object... params) {

			try {
				URL url = new URL(downUrl);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setDoInput(true);
				conn.setConnectTimeout(10000);
				conn.setRequestMethod("GET");
				conn.setRequestProperty("accept", "*/*");
				int resCode = conn.getResponseCode();
				if (resCode != HttpURLConnection.HTTP_OK) {
					publishProgress(-1, "没有找到下载文件");
				}
				int size = ConvertUtils.toInt(conn.getHeaderField("Content-Length"), -1);
				if (size > 0) {
					totalSize = size;
				}
				conn.connect();
				InputStream in = conn.getInputStream();
				File outFile = new File(GlobalVars.getInst().getAttachPath(), FileName);
				FileOutputStream fout = new FileOutputStream(outFile);
				IOUtils.copy(in, fout, size, new MyDownloadListener() {

					@Override
					public void onDownloading(int accepter, int expect) {
						publishProgress(accepter, expect);
					}

				});
				fout.flush();
				if (fout != null) {
					fout.close();
					fout = null;
				}
				if (in != null) {
					in.close();
					in = null;
				}
				if (outFile.exists()) {
					return outFile.getAbsolutePath();
				}
			} catch (MalformedURLException e) {
				publishProgress(-1, new ErrorMsg("network"));
			} catch (IOException e) {
				publishProgress(-1, new ErrorMsg("network.entity.create.stream"));
			} catch (Exception e) {
				publishProgress(-1, new ErrorMsg("network"));
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			clear();
			if (result != null) {
				AndroidUtils.fileInvoke(UpgradeService.this, result.toString());
			}else {
				Toast.makeText(getApplicationContext(), "下载失败,请重新下载", Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		protected void onProgressUpdate(Object... values) {
			if (values != null) {
				int flag = ConvertUtils.toInt(values[0], 0);
				if (flag == -1) {
					Toast.makeText(getApplicationContext(), values[1].toString(), Toast.LENGTH_SHORT).show();
					clear();
					this.cancel(true);
				} else {
					updateProgress(ConvertUtils.toInt(values[0], 0));
				}
			}else {
				clear();
			}

		}

	}

	private void showNotification() {

		// Notification的滚动提示
		String ticker = "正在下载" + FileName;
		// Notification的图标，一般不要用彩色的
		int icon1 = android.R.drawable.stat_sys_download;

		// Notification的Intent，即点击后转向的Activity
		Intent notificationIntent1 = new Intent(this, this.getClass());
		notificationIntent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent contentIntent1 = PendingIntent.getActivity(this, 0, notificationIntent1, 0);

		// 创建Notifcation
		n = new Notification(icon1, ticker, System.currentTimeMillis());
		n.flags |= Notification.FLAG_ONGOING_EVENT;

		// 创建RemoteViews用在Notification中
		RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.service_download_progress);
		contentView.setTextViewText(R.id.notificationTitle, FileName);
		contentView.setTextViewText(R.id.notificationPercent, "0%");
		contentView.setProgressBar(R.id.notificationProgress, totalSize, 10, false);

		n.contentView = contentView;
		n.contentIntent = contentIntent1;

		// 显示这个notification
		nm.notify(GlobalVars.UPGRADE_ID, n);
	}

	private Notification n;

	private void updateProgress(int now) {

		RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.service_download_progress);
		contentView.setTextViewText(R.id.notificationTitle, FileName);
		int percent = now * 100 / totalSize;
		if (percent > 1) {
			contentView.setTextViewText(R.id.notificationPercent, percent + "%");
		}
		contentView.setProgressBar(R.id.notificationProgress, totalSize, now, false);
		n.contentView = contentView;

		nm.notify(GlobalVars.UPGRADE_ID, n);
	}

	@Override
	public void onDestroy() {
		clear();
		Toast.makeText(this, "upgrade service quit", Toast.LENGTH_SHORT).show();
	}

	public void clear() {
		nm.cancel(GlobalVars.UPGRADE_ID);
	}

}
